import {
	orderList,
	delOrder,
	delPassenger,
	cancelOrder,
	SaveSecurityUrl,
	GetTrackingExpress
} from '@/api/order.js'

import {
	getVisaOrderBasicData,
	orderPayMent,
	updatePassengers,
	cashPayment,
	XhsOrderPayResult,
	balancePayment,
	modifyPlannedDepartureDate
} from '@/api/order.js'

import util from '@/utils/util.js';
import {
	is_weixin
} from '@/utils/util.js';
const moment = require('@/utils/moment.js');
moment.locale('en', {
	longDateFormat: {
		l: "YYYY-MM-DD",
	}
});

// import Dialog from "./dialog.vue";
import wanlPayPopup from "./wanlPayPopup.vue";
import authorize from "@/component/authorize/authorize.vue";
let app = getApp()
export default {
	data() {
		return {
			payOrderId: '',
			keyword: '',
			urlImg: getApp().globalData.urlImg,
			themeColor: getApp().globalData.themeColor,
			tabIdx: 0,
			tab: [{
				status: 0,
				name: '全部',
				list: [],
				pageIndex: 0,
				noData: false
			},
			{
				status: 1,
				name: '待支付',
				list: [],
				pageIndex: 0,
				noData: false
			},
			{
				status: 3,
				name: '办理中',
				list: [],
				pageIndex: 0,
				noData: false
			},
			{
				status: 4,
				name: '已完成',
				list: [],
				pageIndex: 1,
				noData: false
			},
			],
			list: [],
			pageSize: 10,
			isGoIndex: true,
			iShidden: true,

			options: [{
				text: '删除',
				style: {
					backgroundColor: '#dd524d',
					width: '100rpx'
				}
			}],
			password: '',
			expireTime: '1',
			// url: '',
			urlShow: false,
			errpassword: false,
			timeOptions: [{
				value: '1',
				label: '1天有效'
			},
			{
				value: '7',
				label: '1周有效'
			},
			{
				value: '30',
				label: '1月有效'
			}
			],
			url: "https://file.aavisa.com/001",
			pageUrl: '',
			currentIndex: 0,
			dialogVisible: false,
			tabs: [{
				name: "全部",
				id: 0,
			},
			{
				name: "待支付",
				id: 1,
			},
			{
				name: "办理中",
				id: 2,
			},
			{
				name: "已完成",
				id: 3,
			},
			],
			paymentIndex: '',
			listColor: [{
				color: '#FD6D04',
				bacground: 'rgba(253, 109, 4, .1)',
				title: '待支付',
				status: [0]
			},
			{
				color: '#1C71F4',
				bacground: 'rgba(28, 113, 244, .1)',
				title: '待预审',
				status: [1001]
			},
			{
				color: '#FD6D04',
				bacground: 'rgba(253, 109, 4, .1)',
				title: '待上传',
				status: [8]
			},
			{
				color: '#0BD0B9',
				bacground: 'rgba(11, 208, 185, .1)',
				title: '已完成',
				status: [3,4,5, 403, 502, 506,507,508]
			},
			{
				color: '#EA262A',
				bacground: 'rgba(234, 38, 42, .1)',
				title: '办理中',
				status: [505, 7, 501]
			}
			],
			backaddress: {}, // 收货地址
			getaddress: {}, // 取件地址( 帮叫顺丰快递去客户取件 客户寄快递)
			myAddress: {}, // 我们的地址
			coupons: [], // 优惠券数据
			travel_date: '', //出行日期
			proposerShow: false, // 编辑出行人
			couponsShow: false, // 优惠券显示
			paymentShow: false, // 支付方式弹层显示
			paymentIndex: '', // 选择的支付方式
			applians: [], // 出行人数据
			docList: [], // 旅客身份
			couponActive: {}, // 当前选择的券
			balance: '', // 余额
			orderInfo: {},
			status: 0,

			isCustomH5: '',
			upInfoShow: false, //编辑联系人信息弹窗

			contactName: '',
			phone: '',
			mark: '',
			ruleMessage: {},

			showPeople: false, //职位身份,
			showPeopleItem: {},
			showPeopleIndex: 0,

			webpay: false,
			order: {},

			minDate: moment(new Date()).format('l'),
			maxDate: moment(new Date().setFullYear(new Date(new Date()).getFullYear() + 8)).format('l'),

			isPay: false, //是否发起支付 
			// 物流信息弹框相关数据
			trackingModalShow: false,
			trackingInfo: null
		}
	},
	components: {
		wanlPayPopup,
		authorize
	},
	onLoad: function (options) {
		let onLaunch_Options = uni.getStorageSync('onLaunch_app')
		let onShow_Options = uni.getStorageSync('onShow_app')
		if (onLaunch_Options && onLaunch_Options.path == 'pages/visa/list' && onLaunch_Options.query) {
			options = onLaunch_Options.query
		} else if (onShow_Options && onShow_Options.path == 'pages/visa/list' && onShow_Options.query) {
			options = onShow_Options.query
		}
		this.setData({
			tabIdx: options.tabIdx || 0,
			payOrderId: options.orderId || '',
		})
		this.onLoadFun();
		if (this.payOrderId) {
			this.continueOrder(this.payOrderId);
		}
		

	},
	onShow: function () {
		console.log("onshow")
		// this.iShidden = !util.checkLogin();
		// getApp().globalData.isLog = util.checkLogin();
		// await this.$refs.auth.setAuthStatus();
  //       await this.waitForLog();
		if (getApp().globalData.isLog) {
			this.tab[this.tabIdx].list = []
			this.setData({
				list: [],
				pageIndex: 1
			}, () => {
				this.getData(true)
			})
		}

	},
	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {
		// 调用 stopPullDownRefresh 停止下拉刷新

		// xhs.stopPullDownRefresh({
		//   success: (res) => {
		//     console.log('停止下拉刷新成功:', res.errMsg);
		//   },
		//   fail: (err) => {
		//     console.error('停止下拉刷新失败:', err.errMsg);
		//   },
		//   complete: () => {
		//     console.log('stopPullDownRefresh 调用结束');
		//   }
		// });

		console.log("onPullDownRefresh")
		this.getData(true)
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {
		if (this.tab[this.tabIdx].noData) return;
		this.getData()
	},
	methods: {
		copyDeilverCode(e) {
			var code = e.currentTarget.dataset.code;
		  uni.setClipboardData({
		    data: code,
		    success: () => {
		      // uni.showToast({
		      //   title: '复制成功',
		      //   icon: 'success',
		      //   duration: 2000
		      // })
		    }
		  })
		},
		getTrackingExpress(e) {
			let orderId = e.currentTarget.dataset.id
		  console.log(orderId)
		  GetTrackingExpress({
		    Id: orderId
		  }).then(res => {
		    if (res.status == 200 && res.data.code == 200) {
		      this.trackingInfo = res.data.data;
		      this.trackingModalShow = true;
		    } else {
		      uni.showToast({
		        title: '获取物流信息失败',
		        icon: 'none',
		        duration: 2000
		      });
		    }
		  }).catch(err => {
		    uni.showToast({
		      title: '获取物流信息失败',
		      icon: 'none',
		      duration: 2000
		    });
		  })
		},
		onBack() {
			uni.navigateBack({
				delta: 1
			})
		},
		getStatusColorAndTitle(status) {
			if (status.OrderStatus == 506 && status.PaymentStatus != 1) {
				return {
					color: '#EA262A',
					title: '待支付',
					bacground: 'rgba(234, 38, 42, .1)',
				}
			}
			else if (status.PaymentStatus == 1 && status.OrderStatus == 0) {
				return {
					color: '#EA262A',
					bacground: 'rgba(234, 38, 42, .1)',
					title: '办理中'
				}
			}


			return this.listColor.find(item => {
				if (Array.isArray(item.status)) {
					return item.status.includes(status.OrderStatus);
				} else {
					return item.status === status.OrderStatus;
				}
			}) || {
				color: '#333',
				title: status.statusZH,
				bacground: 'rgba(0, 0, 0, .1)',

			};
		},
		async getVisaOrderData(orderId) {
			uni.showLoading({
				title: '请稍后',
				mask: true
			})
			getVisaOrderBasicData(orderId).then(res => {
				uni.hideLoading()
				Object.keys(res.data.applians).forEach(k => {
					Object.keys(res.data.docList).forEach(i => {
						if (res.data.applians[k].PeopleType == res.data.docList[i].cn_name) {
							res.data.applians[k].docId = i;
						}
					})
				})
				Object.keys(res.data.coupons).forEach(i => {
					res.data.coupons[i].takeeffectTime = moment(res.data.coupons[i].takeeffectTime)
						.format('l')
					res.data.coupons[i].invalidTime = moment(res.data.coupons[i].invalidTime).format(
						'l')
				})
				let activeCoupon = {}
				if (res.data.currentCoupon.length > 0) {
					activeCoupon = res.data.currentCoupon[0]
					console.log('进入1')
				} else if (res.data.coupons) {
					activeCoupon = res.data.coupons[0]
					console.log('进入2')
				}

				this.setData({
					applians: res.data.applians,
					travel_date: res.data.applians.length > 0 ? res.data.applians[0].PlanStartTime : '',
					backaddress: res.data.backaddress || {},
					getaddress: res.data.getaddress || {},
					myAddress: res.data.myAddress || {},
					orderInfo: res.data.orderInfo || {},
					order: res.data.order || {}, //物流信息 
					docList: res.data.docList || [],
					coupons: res.data.coupons || [],
					//couponActive: res.data.coupons[0] || {},
					role: getApp().globalData.userInfo.role || 0,
					mark: res.data.mark,
					contactName: res.data.contactName || '掌上通签证',
					phone: res.data.phone || 13888888888,
					couponActive: activeCoupon || [],
					radio: res.data.getaddress ? '2' : '1',
					status: res.data.status,

					isCustomH5: res.data.applians[0].Url.indexOf('/allstate')
				})

				if (this.orderInfo.VisaId == "8ddab829e1c743b3b8a5b12f4ca1d478" || this.orderInfo.visaId ==
					'd5de6d1979f04a30bcd1008b36e197d2' || this.orderInfo.visaId ==
					'a490f713da3d4a11b42f969a38964c18' || this.orderInfo.IsAuto == true) {
					// this.checkOrder()
				}
				console.log("orderInfo", this.orderInfo, res.data.orderInfo, res.data.applians[0].Url.indexOf(
					'/allstate'))
				first = false;

			}).catch(err => {
				uni.hideLoading()
				throw err
			})
		},
		// checkOrder() {
		// 	if (!this.travel_date) {
		// 		return app.Tips({
		// 			title: `请选择出行日期!`
		// 		})
		// 	}
		// 	else if (!this.contacttName || !this.phone) {
		// 		return app.Tips({
		// 			title: `请完善订单联系人信息!`
		// 		})
		// 	} else if (!/^1[3456789]\d{9}$/.test(this.phone)) {
		// 		return app.Tips({
		// 			title: `请输入正确的订单联系人电话!`
		// 		})
		// 	}

		// 	this.submitOrder();
		// },

		// 提交订单
		async submitOrder(orderid) {
			// uni.showLoading({
			// 	title: '请稍后',
			// 	mask: true
			// })
			let that = this;
			let data = {
				departureTime: this.travel_date,
				backAddressId: this.backaddress.Id,
				orderId: orderid,
				couponId: this.couponActive.id,
				hasSF: this.orderInfo.HasSF,
				contactName: this.contactName,
				phone: this.phone,
				mark: this.mark,
			}
			if (this.orderInfo.HasSF > 0) {
				data.getAddressId = this.getaddress.Id
			}
			let res = await orderPayMent(data);
			if (res.status == 200) {
				if (this.balance >= (this.orderInfo.Price * this.applians.length - (this
					.couponActive.money ? this.couponActive.money : 0)).toFixed(2)) {
					this.setData({
						paymentIndex: '1'
					})
				} else {
					this.setData({
						paymentIndex: '2'
					})
				}

				this.payNow(orderid);
			} else {
				uni.showToast({
					title: '下单失败_请重新提交',
					duration: 2000
				})
			}
			uni.hideLoading()
		},
		 // 等待登录状态
		        async waitForLog() {
		            for (let index = 0; index < 10; index++) {
		                if (!app.globalData.isLog) {
		                    await new Promise(resolve => setTimeout(resolve, 2000));
		                    console.log("等待登录状态...");
		                } else {
		                    break;
		                }
		            }
		        },
		// 立即支付
		async payNow(orderId) {
			let that = this;
			uni.showLoading({
				title: '请稍后',
				mask: true
			})
			let params = {
				orderId: orderId,
				appId: app.globalData.appid,
				payType: "JSAPI" // MWEB H5
			}
			params.payType = is_weixin() ? 'JSAPI' : 'MWEB';

			console.log("params", params)
			// let that = this;
			console.log(this.paymentIndex)
			if (this.paymentIndex == '2') { // 微信支付
				let wxData = await cashPayment(params);
				debugger
				console.log(wxData, '微信支付')
				if (wxData.status == 200) {
					let hasSF = this.orderInfo.HasSF > 0
					// this.orderInfo.HasSF >0 && this.radio == '2' && JSON.stringify(this.getaddress) && JSON.stringify(this.getaddress)!='{}'  
					// #ifdef H5
					if (!is_weixin()) {
						this.setData({
							webpay: true
						})
						// uni.redirectTo({
						// 	url: `/pages/visa/successful?orderId=${that.orderId}&isSF=${hasSF}`
						// })
						that.getData(true);
						// // 测试
						// uni.redirectTo({
						// 	url: '/pages/order/orderDetail?orderId=' + that.orderId
						// })
						// window.location.replace(wxData.data.mweb_url);
					} else {

						WeixinJSBridge.invoke(
							'getBrandWCPayRequest', {
							"appId": wxData.data.appId, //公众号名称，由商户传入     
							"timeStamp": wxData.data.timeStamp, //时间戳，自1970年以来的秒数     
							"nonceStr": wxData.data.nonceStr, //随机串     
							"package": wxData.data.prepayId,
							"signType": wxData.data.signType, //微信签名方式：     
							"paySign": wxData.data.paySign //微信签名 
						},
							function (res) {
								if (res.err_msg == "get_brand_wcpay_request:ok") {
									console.log('成功')

									that.getData(true);
									// uni.redirectTo({
									// 	url: '/pages/order/orderDetail?orderId=' + that.orderId
									// })
									// 使用以上方式判断前端返回,微信团队郑重提示：
									//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
								} else {
									isPay = false
								}
							});
					}
					// #endif 

					// #ifdef MP-ALIPAY 
					if (wxData.data == '交易成功') {
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							duration: 300
						});
						debugger
						// 						let url = `/pages/visa/successful?orderId=${that.orderId}&isSF=${hasSF}`;
						// 						uni.redirectTo({
						// 							url: url
						// 						});
						that.getData(true);
						// _self.openDetail();
						return;
					}
					uni.tradePay({
						tradeNO: wxData.data,
						success: (res) => {
							if (res.resultCode == '9000') {
								uni.showToast({
									title: '支付成功',
									icon: 'success',
									duration: 300
								});
								debugger
								// let url =
								// 	`/pages/visa/successful?orderId=${that.orderId}&isSF=${hasSF}`;
								// uni.redirectTo({
								// 	url: url
								// });
								that.getData(true)
							}
						},
						fail: (res) => {
							console.log(res)
							uni.showToast({
								title: '数据出错,请稍后再试',
								icon: 'error',
								duration: 500
							});
						}
					});

					// #endif 

					// #ifdef MP-XHS
					if (wxData.data == '交易成功') {
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							duration: 300
						});
						let url = `/pages/visa/successful?orderId=${that.orderId}&isSF=${hasSF}`;
						uni.redirectTo({
							url: url
						});

						// _self.openDetail();
						return;
					}
					xhs.requestGuaranteeOrderPayment({
						orderInfo: {
							payToken: wxData.data.token, // 支付凭证
							orderId: wxData.data.OutOrderNo, // 订单 ID
							//orderId: that.order.orderno   // 订单 ID
						},
						success: async function (res) {
							console.log('支付成功:', wxData.data.token);
							let data = {
								PayData: wxData.data.token
							};


							uni.showLoading({
								title: '请稍后',
								mask: true
							})
							try {
								console.log("支付回调参数", data);
								await XhsOrderPayResult(data);
							} catch (e) {
								console.log(e)
							}

							// XhsOrderPayResult(data).then(res1=>{
							// 	console.log(res1);
							// }).catch(err=>{
							// 	console.log(err)
							// })

							uni.hideLoading();
							// let url = `/pages/visa/successful?orderId=${that.orderId}&isSF=${hasSF}`;
							// uni.navigateTo({
							// 	url: url
							// });
							that.getData(true)


						},
						fail: (err) => {
							console.error('支付失败:', err.errMsg);
						},
						complete: () => {
							console.log('requestGuaranteeOrderPayment 调用结束');
						}
					});

					// #endif
					// #ifdef MP-WEIXIN
					if (wxData.status == 200) {
						let res = JSON.parse(JSON.parse(wxData.data))
						console.log(res, '微信支付')
						uni.hideLoading()
						wx.requestPayment({
							timeStamp: res.timeStamp,
							nonceStr: res.nonceStr,
							package: res.package,
							signType: res.signType,
							paySign: res.paySign,
							success: res => {
								// if(that.data.orderInfo.VisaId == "8ddab829e1c743b3b8a5b12f4ca1d478" || that.data.orderInfo.VisaId == "a490f713da3d4a11b42f969a38964c18"|| that.data.orderInfo.VisaId == "30e77709280f4486aeaed0836ae1ea64" || this.data.orderInfo.IsAuto)
								// {
								//   uni.redirectTo({
								//     url: '/pages/order/order?orderId=' + this.data.orderId
								//   })
								//   return
								// }
								// wx.redirectTo({
								//   url: '/pages/orderDetailB/index?orderId=' + this.data.orderId
								// })
								that.getData(true)
							},
							fail(res) {
								console.log(res)
								uni.hideLoading()
							}
						})
					}
					// #endif
				} else {
					uni.showToast({
						title: wxData.message,
						icon: 'none',
						duration: 3000
					});
				}


			} else {
				uni.showModal({
					title: '提示',
					content: `您本次将支付${this.orderInfo.Price * this.applians.length - (this.couponActive.money ? this.couponActive.money : 0)}元`,
					success: async res => {
						if (res.confirm) {
							console.log('用户点击确定')
							let balanceData = await balancePayment(this.orderId); // 余额支付
							console.log(balanceData, '余额支付')
							if (balanceData.status == 200) {
								uni.redirectTo({
									url: '/pages/order/orderDetail?orderId=' + this
										.orderId
								})
							} else {
								uni.showToast({
									title: balanceData.message,
									icon: 'none',
									duration: 3000
								});
							}
						} else if (res.cancel) {
							console.log('用户点击取消')
						}
					}
				})

			}
			uni.hideLoading()
		},

		handleCose() {
			this.dialogVisible = false;
		},
		pay() {
			this.$refs.popup.open();
		},
		close(isOk) {
			console.log(isOk)
			this.dialogVisible = isOk;
		},
		onTabChange(e) {
			let tabIdx = e
			this.tabIdx = tabIdx
			if (!this.tab[tabIdx].noData) return this.getData()
		},
		onLoadFun: function () {
			console.log('onLoadFun')
			this.setData({
				list: [],
				pageIndex: 1
			}, () => {
				this.getData(true)
			})
		},

		onCloseAuto(e) {
			console.log(e)
		},

		getData(reset = false) {
			// #ifndef MP-XHS
			uni.showNavigationBarLoading()
			// #endif
			let data = {
				pageIndex: this.tab[this.tabIdx].pageIndex + 1,
				pageSize: this.pageSize,
				status: this.tab[this.tabIdx].status,
				key: this.keyword
			}
			if (reset) {
				data.pageIndex = 1
				this.setData({
					[`tab[${this.tabIdx}].pageIndex`]: 1
				})
			}

			orderList(data).then(res => {
				let list = res.data.DataList || []
				this.setData({
					[`tab[${this.tabIdx}].list`]: reset ? list : this.tab[this.tabIdx]
						.list.concat(list),
					[`tab[${this.tabIdx}].noData`]: list.length >= data.pageSize ? false : true,
					[`tab[${this.tabIdx}].pageIndex`]: this.tab[this.tabIdx].pageIndex +
						1
				})
				// #ifndef MP-XHS
				uni.hideNavigationBarLoading()
				// #endif
				uni.stopPullDownRefresh()
			})
				.catch(err => {
					console.log("异常", err)
					app.Tips({
						title: err
					})
				})
		},
		isThirtyDaysAgo(dateStr) {
		    // 解析输入日期
		       const inputDate = new Date(dateStr);
		       
		       // 获取当前日期并清除时间部分
		       const currentDate = new Date();
		       currentDate.setHours(0, 0, 0, 0);
		       
		       // 计算30天前的日期（毫秒数）
		       const thirtyDaysInMs = 30 * 24 * 60 * 60 * 1000;
		       const thirtyDaysAgo = new Date(currentDate.getTime() - thirtyDaysInMs);
		       
		       // 比较日期（只比较年月日）
		       const inputDateOnly = new Date(inputDate);
		       inputDateOnly.setHours(0, 0, 0, 0);
		       
		       return inputDateOnly.getTime() <= thirtyDaysAgo.getTime();
		},
		shareUrl(e) {
			debugger
			const url = e.currentTarget.dataset.name;

			this.pageUrl = url;
			this.dialogVisible = true
		},
		onExpireTimeChange(days) {
			this.expireTime = days;

		},
		// 关闭弹窗
		onClose() {
			this.urlShow = false
			this.password = ''
			this.errpassword = false
		},

		// 保存安全链接
		SaveSecurityUrl() {
			if (!this.password) {
				this.errpassword = true
				this.urlShow = true
				app.showToast('请输入密码')
				return
			}

			uni.showLoading({
				title: '生成链接中'
			})

			// 调用后端API生成安全链接
			SaveSecurityUrl({
				url: this.url,
				password: this.password,
				expireTime: parseInt(this.expireTime)
			}).then(res => {
				uni.hideLoading()
				this.urlShow = false
				if (res.status === 200) {
					uni.setClipboardData({
						data: res.data.url,
						success: () => {
							app.showToast('链接已复制到剪贴板')
							this.onClose()
						}
					})
				} else {
					app.showToast(res.message || '生成链接失败')
				}
			}).catch(() => {
				uni.hideLoading()
				app.showToast('网络错误，请重试')
			})
		},
		tapOrderProgress(e) {
			console.log(e)
			// debugger
			let {
				id,
				unionid,
				totalpaystatus,
				status
			} = e.currentTarget.dataset
			// app.goToPage(`/pages/order/orderDetailB/orderDetailB?orderId=${id}&orderStatus=${status}`)
			if (status == 4 || status == 3) return app.goToPage(
				`/pages/order/orderDetailB/orderDetailB?orderId=${id}&orderStatus=${status}`)
			if (status == 0) {
				// app.goToPage(`/pages/dataProgress/dataProgress?orderId=${id}&active=1`)

				app.goToPage(`/pages/order/orderDetailB/orderDetailB?orderId=${id}&orderStatus=${status}`)
			}
			if (status == 1) {
				// app.goToPage(`/pages/dataProgress/dataProgress?orderId=${id}&acitve=2`)
				app.goToPage(`/pages/order/orderDetailB/orderDetailB?orderId=${id}&orderStatus=${status}`)
			}
		},

		tapUpload(e) {
			debugger
			let that = this;
			console.log(e, 'tapUpload')
			let item = e.currentTarget.dataset.item
			let orderid = e.currentTarget.dataset.id
			let status = e.currentTarget.dataset.status
			let visaPage = e.currentTarget.dataset.visapage
			let PaymentStatus = e.currentTarget.dataset.paymentStatus
			let visaTitleSM = e.currentTarget.dataset.visaTitleSM
			let name = e.currentTarget.dataset.name;

			if (item.status == 1) {
				if (visaTitleSM == '马来西亚入境卡MDAC') {
					uni.showModal({
						title: '温馨提示',
						content: '请您稍后，大约需要5-10分钟后，\r\n可以下载入境卡，如还未出，请点右\r\n侧客服按钮与我们的客服联系。',
						success: res => {
							that.getData(true)
						}
					})
					return
				}

				if (visaTitleSM == '新加坡入境卡ICA' ||
					visaTitleSM == '印度尼西亚入境卡' ||
					visaTitleSM == '泰国数字入境卡') {

					let str = name
					let regex = /\(([^)]+)\)/
					let match = str.match(regex)
					let dateInParentheses = match ? match[1] : null

					console.log(dateInParentheses)

					function daysBetween(dateString) {
						const today = new Date()
						const todayFormatted = `${today.getMonth() + 1}-${today.getDate()}`
						const currentYear = today.getFullYear()
						const d1 = new Date(`${currentYear}-${todayFormatted}`)
						const d2 = new Date(`${currentYear}-${dateString}`)
						const diffTime = Math.abs(d2 - d1)
						return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
					}

					if (daysBetween(dateInParentheses) <= 2) {
						uni.showModal({
							title: '温馨提示',
							content: '请您稍后，大约需要3分钟后，可以下载入境卡，如还未出，请点右侧客服按钮与我们的客服联系。',
							success: res => {
								that.getData(true)
							}
						})
						return
					}

					function parseDate(dateStr) {
						let parts = dateStr.split('-')
						let month = parseInt(parts[0], 10) - 1
						let day = parseInt(parts[1], 10)
						let currentDate = new Date()
						return new Date(currentDate.getFullYear(), month, day)
					}

					try {
						let dateObj = parseDate(dateInParentheses)
						dateObj.setDate(dateObj.getDate() - 2)

						function formatDate(date) {
							let month = (1 + date.getMonth()).toString().padStart(2, '0')
							let day = date.getDate().toString().padStart(2, '0')
							return month + '-' + day
						}

						let formattedPreviousDate = formatDate(dateObj)
						console.log(formattedPreviousDate)
						uni.showModal({
							title: '温馨提示',
							content: `根据移民局规定，只能在入境三天内提交申请，我们会在${formattedPreviousDate}为您提交申请，并发送入境卡到您的邮箱，您也可以在订单列表下载入境卡。`,
							success: res => {
								that.getData(true)
							}
						})
					} catch (e) {
						console.log(e)
					}

					that.getData(true)
					return
				}

				if (visaTitleSM == "印度尼西亚电子签证") {
					uni.showModal({
						title: '温馨提示',
						content: '请您稍等，工作日(09:00-18:00)，一般2小时内出签，如特殊情况，请联系客服加急',
						success: res => {
							that.getData(true)
						}
					})
					that.getData(true)
					return
				}
			}

			// debugger
			console.log(status, "status")
			console.log(item.status, "item.status ")
			if (item.status == 506 && PaymentStatus == 1) {
				return app.goToPage(`/pages/downloadVisa/index?orderId=${item.Id}`)
			}
			if ((status == 3 || status == 4 || status == 0) && !visaPage) {
				// return app.goToPage(`/pages/order/orderDetailB/orderDetailB?orderId=${orderid}`)
			} else if (item.status == -1) {
				app.goToPage(`/pages/downloadVisa/index?orderId=${item.Id}`)
			} else if (item.status > 0 && PaymentStatus == 1) {
				return app.goToPage(`/pages/downloadVisa/index?orderId=${item.Id}`)
			} else {
				// return app.goToPage(`/pages/order/orderDetail?orderId=${orderid}`)
			}
			let memberid = getApp().globalData.userInfo.MemberId;
			let url = encodeURIComponent(item.url + "&memberid=" + memberid + "&newui=true")
			getApp().goToPage(`/pages/uploadDataByH5/index?url=${url}`)
		},
		isMoreThan30SecondsAgo(timestamp) {
			console.log(timestamp)
			if (!timestamp) {
				// 如果时间戳不存在或者为空，则直接返回 false。
				return true;
			}
			const givenTime = new Date(timestamp.replace(/-/g, '/'));
			const currentTime = new Date();

			// 计算两个时间点之间的差值并转换为秒。
			const diffInSeconds = Math.floor((currentTime - givenTime) / 1000);

			// 返回布尔值表明是否已经过去至少30秒。
			return diffInSeconds >= 30;
		},
		isMoreThan30DayAgo(timestamp) {
			console.log(timestamp)
			if (!timestamp) {
				// 如果时间戳不存在或者为空，则直接返回 false。
				return true;
			}
			const givenTime = new Date(timestamp);
			const currentTime = new Date();

			// 计算两个时间点之间的差值并转换为天数。
			const diffInDays = Math.floor((currentTime - givenTime) / (1000 * 60 * 60 * 24));

			// 返回布尔值表明是否已经过去至少30天。
			return diffInDays >= 30;
		},
		refresh() {
			uni.showToast({
				title: "正在处理支付请求，请稍后",
				icon: 'none'
			})
			this.getData(true)
		},
		// 设置出行人选中
		passengerItemCheck(e) {
			return false
			let {
				idx,
				pIdx,
				status,
				id
			} = e.currentTarget.dataset

			// if (status > 2) {
			// 	return app.goToPage(`/pages/order/orderDetail?orderId=${id}&orderStatus=${status}`)
			// }
			console.log('passengerItemCheck')
			return app.goToPage(`/pages/order/orderDetailB/orderDetailB?orderId=${id}&orderStatus=${status}`)

			// let o = this.tab[this.tabIdx].list[idx]
			// let p = o.PassengerItem[pIdx]
			// if (p.paystatus !== 0) return;
			// // if (p.statusZH == "等待上传资料" && p.TaskTable == 100) p.statusZH="查看资料";
			// if (p.hasOwnProperty('checked')) {
			// 	p.checked = !p.checked
			// } else {
			// 	p.checked = true
			// }
			// this.setData({
			// 	[`tab[${this.tabIdx}].list[${idx}].PassengerItem[${pIdx}]`]: p
			// })
		},

		onCloseAuto: function () {
			this.setData({
				iShidden: true
			});
		},

		//取消订单
		cancelOrder(e) {
			debugger
			let order = this.tab[this.tabIdx].list[e.currentTarget.dataset.idx]
			// console.log(this)
			console.log(this.tabIdx)
			console.log(e.currentTarget.dataset.idx)
			console.log(order, 'order')
			if (order.Status != 1 && order.Status != 0) return;
			uni.showModal({
				title: '提示',
				content: '确定取消订单？',
				confirmColor: this.themeColor,
				success: res => {
					if (res.cancel) return;
					cancelOrder(order.Id).then(res => {
						getApp().Tips({
							title: '订单已取消',
							icon: 'success'
						})
						this.getData(true)
					}).catch(err => {
						console.log(err)
						getApp().Tips({
							title: err
						})
					})
				}
			})
		},
		//删除订单
		delOrder(e) {
			let order = this.tab[this.tabIdx].list[e.currentTarget.dataset.idx]
			// console.log(this)
			console.log(this.tabIdx)
			console.log(e.currentTarget.dataset.idx)

			if (order.Status != -1) return;
			uni.showModal({
				title: '提示',
				content: '确定删除订单？',
				confirmColor: this.themeColor,
				success: res => {
					if (res.cancel) return;
					delOrder(order.Id).then(res => {
						getApp().Tips({
							title: '订单已删除',
							icon: 'success'
						})
						this.getData(true)
					}).catch(err => {
						console.log(err)
						getApp().Tips({
							title: err
						})
					})
				}
			})
		},
		//继续办理
		continueOrder(id) {
			console.log(id, 'continueOrder')
			let that = this;
			this.getVisaOrderData(id).then(() => {
				that.submitOrder(id)
			});

			// let order = this.tab[this.tabIdx].list[e.currentTarget.dataset.idx];
			// app.goToPage(`/pages/visa/dataProgress?orderId=${order.Id}&status=${order.Status}`)
		},

		goInvoice(e) {
			console.log('goInvoice')

			let order = this.tab[this.tabIdx].list[e.currentTarget.dataset.idx];
			app.goToPage(
				`/pages/invoice/index?amount=${order.FinishGetMoney}&InvoiceNo=${order.InvoiceNo}&order=${order.Id}`
			)
		},
		continueInvoice(e) {
			console.log('goInvoice')

			let order = this.tab[this.tabIdx].list[e.currentTarget.dataset.idx];
			app.goToPage(
				`/pages/invoice/index?amount=${order.FinishGetMoney}&InvoiceNo=${order.InvoiceNo}&order=${order.Id}`
			)
		},
		getOrderNo(str) {
			try {
				var result = str.substr(6, 4) + str.substr(14, 3);
				return result
			} catch (e) {
				console.log(e)
				return str
			}

		},
		//删除申请人
		onDelPassenger(item, idx, pIdx) {
			console.log("item,idx,pIdx", item, idx, pIdx)
			let order = this.tab[this.tabIdx].list[idx];
			if (item.status != 0 || order.PaymentStatus == 1 || order.PassengerItem.length == 1)
				return this.tab[this.tabIdx].list[idx].PassengerItem[pIdx].show = false; //instance.close()
			uni.showModal({
				title: '提示',
				content: `确定删除${item.PassengerName}的出行信息？`,
				success: res => {
					if (res.cancel) return;

					delPassenger(item.Id).then(res => {
						getApp().Tips({
							title: res.message,
							icon: 'success'
						})

						order.PassengerItem.splice(pIdx, 1);
						this.setData({
							[`tab[${this.tabIdx}].list[${idx}]`]: order
						});

					}).catch(err => {
						getApp().Tips({
							title: err
						})
					})
				},
				// complete: () => {
				// 	return this.tab[this.tabIdx].list[idx].PassengerItem[pIdx].show = false; //instance.close();
				// }
			})
		},
		noop() { },
		// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
		open(idx, pIdx) {
			console.log(this.tab[this.tabIdx].list[idx].PassengerItem[pIdx], idx, pIdx)
			// return 
			// this.tab[this.tabIdx].list[idx].PassengerItem[pIdx].show = false;
			this.tab[this.tabIdx].list[idx].PassengerItem.map((val, index) => {
				this.tab[this.tabIdx].list[idx].PassengerItem[index].show = false;
			})

		}

	},

}